<template>
	<div>
		省市县三级联动
		<el-select placeholder="请选择省" 
			v-model="province" 
			style="width:200px">
			<el-option v-for="item in areaDataRef" 
			:value="item.code"
			:key="item.code"
			:label="item.name"/>
		</el-select>
		<el-select :disabled="!province" 
			style="margin: 0px 10px;width:200px" 
			placeholder="请选择市" 
			v-model="city"  >
			<el-option   v-for="item in selectCity" 
			:value="item.code"
			:key="item.code"
			:label="item.name"/>
		</el-select>
		<el-select :disabled="!city"  
			placeholder="请选择县" 
			v-model="area" 
			style="width:200px">
			<el-option v-for="item in selectArea" 
			:value="item.code"
			:key="item.code"
			:label="item.name"/>
		</el-select>
	</div>
</template>

<script lang="ts" setup>
	import {watch, ref} from 'vue'
	import areaData from '../../../views/chooseArea/pca-code.json'
 
	// console.log(areaData)
	let   province=ref<string>('');
	let city=ref<string>('')
	let area=ref<string>('')
	let areaDataRef=ref(areaData)
	let selectCity=ref<AreaItem[]>([])
	let selectArea=ref<AreaItem[]>([])
	// 定义数据类型
	export interface AreaItem{
		name:string,
		code:string,
		children?:AreaItem[]
	}
	export interface AreaData{
		name:string,
		code:string
	}
	let emits=defineEmits(['change'])
	// 监听省的变化实现联动
	watch(()=>province.value,val=>{
		if(val){ 
				let cities= areaDataRef.value.find(item=>item.code===province.value)!.children!
				selectCity.value= cities
		}
		city.value=''
		area.value=''
	})
	// 监听市的变化实现联动
	watch(()=>city.value,val=>{
		if(val){ 
				let cities= selectCity.value.find(item=>item.code===city.value)!.children!
				selectArea.value= cities
		}
	})
	// 监听区县的变化实现联动
	watch(()=>area.value,val=>{
		if(val){
			let provinceData:AreaData={
				code:province.value,
				name:province.value && areaDataRef.value.find(item=>item.code===province.value)!.name
			}
			let cityData:AreaData={
				code:city.value,
				name:city.value && selectCity.value.find(item=>item.code===city.value)!.name
			}
			let areaData:AreaData={
				code:val,
				name:val && selectArea.value.find(item=>item.code===val)!.name
			}
			 emits('change',{
				 province:provinceData,
				 city:cityData,
				 area:areaData})
		}
	})
</script>

<style lang="scss" scoped>
</style>